import json
import time


class LoginHandler:
    __browser_key = "32a08689cbe113360690e07a0a0f9d9c"

    def __init__(self, client, username: str, password: str):
        self.client = client

        self.username = username
        self.password = password

        self.code = None
        self.pub_key = None
        self.pre_login()

    def pre_login(self):
        url = "https://www.imooc.com/passport/user/prelogin"
        response = self.client.session.post(url)
        json_data = response.json()

        assert json_data["status"] == 10001, json_data

        self.code = json_data["code"]
        self.pub_key = json_data["pubkey"]

    def check_captcha(self) -> bool:
        url = "https://www.imooc.com/passport/user/loginverifyshow"
        params = {
            "username": self.username,
        }

        response = self.client.session.get(url, params=params)
        json_data = response.json()

        if json_data["status"] == 10001:
            return True
        elif json_data["status"] == 90005:
            return False
        else:
            raise Exception(json_data)

    def get_captcha(self) -> str:
        url = "https://www.imooc.com/passport/user/verifycode"
        params = {
            "t": str(int(time.time() * 1000)),
        }

        while True:
            response = self.client.session.get(url, params=params)
            with open("captcha.jpg", "wb") as f:
                f.write(response.content)

            captcha = input("输入图片验证码:")
            if self.verify_captcha(captcha):
                return captcha
            else:
                print("验证码错误，刷新验证码重试...")

    def verify_captcha(self, captcha: str) -> bool:
        url = "https://www.imooc.com/passport/user/verifycheck"
        params = {
            "verify": captcha,
        }
        response = self.client.session.get(url, params=params)
        json_data = response.json()
        return json_data["status"] == 10001

    def _login(self, captcha: str):
        url = "https://www.imooc.com/passport/user/login"

        data = {
            "username": self.username,
            "password": self.password,
            "verify": captcha or "",
            "remember": 1,
            "pwencode": 0,
            "browser_key": self.__browser_key,
            "referer": "https://www.imooc.com",
        }

        response = self.client.session.post(url, data=data)
        json_data = response.json()

        if json_data["status"] == 10001:
            login_url = json_data["data"]["url"][0]
            params = {
                "callback": "callback",
                "_": str(int(time.time() * 1000)),
            }
            response = self.client.session.get(login_url, params=params)
            print("登录成功", json.loads(response.content.replace(b"callback(", b"", 1)[:-1]))
        else:
            raise Exception(json_data)

    def login(self):
        captcha = self.get_captcha() if self.check_captcha() else None
        self._login(captcha)
